//
//  DMGoodsIntroduceTableViewCell.m
//  DistributionMallApp
//
//  Created by Jim huang on 2018/10/29.
//  Copyright © 2018年 JHnoplan. All rights reserved.
//

#import "DMGoodsIntroduceTableViewCell.h"
@interface DMGoodsIntroduceTableViewCell ()<UIWebViewDelegate>
@end

@implementation DMGoodsIntroduceTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.webView.delegate = self;
    [self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
    
    self.webView.scrollView.scrollEnabled = NO;
}



#pragma mark ----webView
//监听web高度 自适应拉长
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    if ([keyPath isEqualToString:@"contentSize"]) {
        CGSize webSize = [self.webView sizeThatFits:CGSizeZero];
        self.webViewHeight.constant = webSize.height;
        [self.contentView layoutIfNeeded];
        
        if (self.reloadBlock) {
            self.reloadBlock();
        }
    }
}

#pragma mark ----webView
//图片适配屏幕宽度
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *js = @"function imgAutoFit() { \
    var imgs = document.getElementsByTagName('img'); \
    for (var i = 0; i < imgs.length; ++i) {\
    var img = imgs[i];   \
    img.style.maxWidth = %f;   \
    } \
    }";
    js = [NSString stringWithFormat:js, [UIScreen mainScreen].bounds.size.width - 20];
    
    [self.webView stringByEvaluatingJavaScriptFromString:js];
    [self.webView stringByEvaluatingJavaScriptFromString:@"imgAutoFit()"];
    
    //
    CGSize fittingSize = [self.webView sizeThatFits:CGSizeZero];
    //此处我获取的是网页中倒数第三个标签的位置，可以根据要加载的网页结构设定取倒数第几个标签的位置可以代表整个网页高度
    CGFloat lastHeight =[[self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName(\"body\")[0].children[document.getElementsByTagName(\"body\")[0].children.length-1].offsetTop"] floatValue];
    
    NSLog(@"webView:%@",NSStringFromCGSize(fittingSize));
    
    self.webViewHeight.constant = lastHeight;
    
    if (self.reloadBlock) {
        self.reloadBlock();
    }
    
}

-(void)setH5Str:(NSString *)h5Str{
    _h5Str = h5Str;
    [self.webView loadHTMLString:h5Str baseURL:nil];
}




- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
